<template>
  <view class="chat-layout flex">
    <LeftConverstaions />
    <div class="message-area relative"
      :class="(chatStore.currentSession?.messages || []).length === 0 ? 'no-message' : ''" ref="messagesContainer">
      <MessageList />
      <AskInputer />
    </div>
  </view>
</template>

<script setup lang="ts">
import AskInputer from '@/components/AskInputer/AskInputer.vue';
import LeftConverstaions from '@/components/LeftConverstaions/LeftConverstaions.vue';
import MessageList from '@/components/MessageList/MessageList.vue';
import { nextTick, ref, watch, watchEffect } from 'vue';
import { useChatStore } from '@/store/chatstore';


const messagesContainer = ref<HTMLElement | null>(null);


const chatStore = useChatStore();
// 在scrollToBottom方法中添加边界判断
const scrollToBottom = (immediate = false) => {
  const container = messagesContainer.value;
  if (container) {
    // 计算距离底部50px内视为已在底部
    const isNearBottom = container.scrollHeight - container.scrollTop <= container.clientHeight + 50;

    if (isNearBottom || immediate) {

      container.scrollTo({
        top: container.scrollHeight,
        // behavior: 'smooth'
      });
    }
  }
};


watch(() => chatStore.currentStreamContent, (n) => {
  if (n) {
    console.log('enter scrolltoBoootm')
    nextTick(() => {
      scrollToBottom(true);
    })

  }
})

watch(() => chatStore.currentSessionId, (n) => {
  if (n) {
    console.log('enter scrolltoBoootm')
    nextTick(() => {
      scrollToBottom(true);
    })
  }

})
</script>

<style lang="scss" scoped>
.chat-layout {
  height: 100vh;

  .message-area {
    height: 100%;
    width: calc(100vw - 300px);
    background-color: #fff;
    //  &.no-message {
    //     display: flex;
    //     justify-content: center;
    //     align-items: center;
    //     flex-direction: column;
    //   }

    overflow-y: auto;
    ;
  }
}
</style>
